//
//  ViewController.m
//  SectionAnimation
//
//  Created by huangyibiao on 19/02/15.
//  Copyright © 2019年 aiden. All rights reserved.
//

#import "menuViewController.h"
#import "HYBSectionModel.h"
#import "HYBHeaderView.h"

#import "../MKConstant.h"
#import "../DB/DataPersist.h"
#import "../ItemViewController.h"
#import "MenuTbCell.h"
#import "../getReportVC.h"

#import "../promotion/promotionTVC.h"

#import "../contactTVC2.h"

#import "aboutUs/UIScrollView的快速使用-Bridging-Header.h"
#import "UIScrollView的快速使用-Swift.h"

#import "../LoginViewController3.h"
#import "../DataSource.h"

static NSString *kCellIdentfier = @"UITableViewCell";
static NSString *kHeaderIdentifier = @"HeaderView";

@interface menuViewController () <UITableViewDelegate, UITableViewDataSource>{
    NSMutableArray *indexArray;    
    NSMutableArray *menuarr;
    ItemViewController *itemVc; //子頁面
    promotionTVC *proTVC; //预约頁面

    contactTVC2 *contvc2;
    LoginViewController3 *LoginVC; //登录頁面
    getReportVC *getreportvc; //登录頁面
    
    NSArray *titlearr1;
    NSArray *titlearr2;
    BOOL islogin;
    BOOL ismenufirst;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *sectionDataSources;

@end

@implementation menuViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  ismenufirst = false;
    
   
  titlearr1 = @[@"我的檢測報告",@"皇牌服務",@"全方位健康管理",@"promotion",@"關於Young+",@"聯絡Young+",@"登出"];
  titlearr2 = @[@"皇牌服務",@"全方位健康管理",@"promotion",@"關於Young+",@"聯絡Young+",@"登入"];


}
- (void)viewWillAppear:(BOOL)animated{
    
    
    islogin = [[DataSource getInstance]getLoginFlag];
    
    if ([[DataPersist readValuePre:@"loginStatus"] isEqualToString:@"1"]) {
        islogin = true;
        [[DataSource getInstance]setLoginFlag:true]; //設置登錄狀態
    }

    NSLog(@"islogin %d",islogin);
    
    
    NSString *wpuserid =  [DataPersist readValuePre:@"wpuid"] ; //用户UID
    NSLog(@"wpuserid %@",wpuserid);
    
    [self setMenuData];
    indexArray = [[NSMutableArray alloc]init];
    
    if (islogin) {
        [indexArray addObject:@"0"];  //增加section
    }
    
    for (NSArray *array in menuarr) {
        NSDictionary *dic = [array firstObject];
        NSString *cate = [dic valueForKey:@"cate"];
        [indexArray addObject:cate];
    }
   // NSLog(@"menuarr %@",menuarr);
    
    
    [indexArray addObject:@"4"];  //增加section
    [indexArray addObject:@"5"];
    [indexArray addObject:@"6"];
    //NSLog(@"indexArray %@",indexArray);
   
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class]
           forCellReuseIdentifier:kCellIdentfier];
    [self.tableView registerClass:[HYBHeaderView class] forHeaderFooterViewReuseIdentifier:kHeaderIdentifier];
    self.tableView.tableFooterView=[[UIView alloc]init]; //去掉tableView多余的空白行分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; //去掉tableView行分割线
}
-(void)viewWillDisappear:(BOOL)animated{
    
}

-(void)setMenuData{
    //读取数组值
    NSMutableArray *MACArray = [[DataPersist readValueNSMutableArray:@"homeindex"] mutableCopy];
    //NSLog(@"MACArray %@ ",MACArray);
    NSMutableArray *dataarr = [MACArray valueForKey:@"data"];
    //NSLog(@"dataarr is %@",dataarr);
    
    
    //字典   包含数组
    NSMutableArray *aceServicesarr = [dataarr valueForKey:@"aceServices"];
    NSArray *arra = [self setnewarr:aceServicesarr cate:@"aceServices"];
    //NSLog(@"arra %@",arra);
    
    NSMutableArray *healthManagementarr = [dataarr valueForKey:@"healthManagement"];
    NSArray *arrb = [self setnewarr:healthManagementarr cate:@"healthManagement"];
    
    NSMutableArray *promotionarr = [dataarr valueForKey:@"promotion"];
    NSArray *arrc = [self setnewarr:promotionarr cate:@"promotion"];
    
    
    NSMutableArray *menuarr2 = [[NSMutableArray alloc]init]; //菜单数组新建
    [menuarr2 addObject:arra];
    [menuarr2 addObject:arrb];
    [menuarr2 addObject:arrc];
    //NSLog(@"menuarr.count %lu",(unsigned long)menuarr2.count);
    
    menuarr = [menuarr2 mutableCopy];
    
   
    //NSLog(@"menuarr.count %lu",(unsigned long)menuarr.count);
    //NSLog(@"menuarr 数据 %@",menuarr);
}
-(NSMutableArray*)setnewarr:(NSMutableArray *)Mutbarr cate:(NSString*)cate{
    
    NSMutableArray * outputarr = [NSMutableArray array];
    
    for (NSMutableDictionary *dicset in Mutbarr) {  //循环。z将数组中值 循环到新数组
        
        //NSString *detail = [dicset valueForKey:@"detail"];
        //NSLog(@"detail %@",detail);
        
        NSMutableDictionary * mFirstDic = [[NSMutableDictionary alloc] init];
        NSArray *array1 = [dicset allKeys];
        
        [mFirstDic setValue:cate forKey:@"cate"];  //设置该分类名称
        
        
        for (int i = 0; i < array1.count; i++) {
            [mFirstDic setValue:[dicset valueForKey:@"detail"] forKey:@"detail"];
            [mFirstDic setValue:[dicset valueForKey:@"id"] forKey:@"id"];
            [mFirstDic setValue:[dicset valueForKey:@"img"] forKey:@"img"];
            [mFirstDic setValue:[dicset valueForKey:@"title"] forKey:@"title"];
        }
        //NSLog(@"mFirstDic %@",mFirstDic);
        
        [outputarr addObject:mFirstDic];
    }
    
    return outputarr;
}

- (NSMutableArray *)sectionDataSources {
    
    BOOL isload = false;
    if (islogin == ismenufirst) { //判断登录状态是否改变，是否需要重新加载数据
        isload = true;
        ismenufirst = !ismenufirst;
    } else {
        isload = false;
    }
    
  if (_sectionDataSources == nil || isload) {
    _sectionDataSources = [[NSMutableArray alloc] init];
      
      NSArray *hadertitlearr = @[];
      
      if (islogin) {
        hadertitlearr = titlearr1;
      }else{
        hadertitlearr = titlearr2;
      }

      
    for (NSUInteger i = 0; i < hadertitlearr.count; i++) {
      HYBSectionModel *sectionModel = [[HYBSectionModel alloc] init];
      sectionModel.isExpanded = NO;
      //sectionModel.sectionTitle = [NSString stringWithFormat:@"section: %ld", i];
      
      sectionModel.sectionTitle = [hadertitlearr objectAtIndex:i];
        
      NSMutableArray *itemArray = [[NSMutableArray alloc] init];
     
       // NSLog(@"%@",[hadertitlearr objectAtIndex:i]);
            //if(i < 3){
          if([[hadertitlearr objectAtIndex:i] isEqualToString:@"皇牌服務"] || [[hadertitlearr objectAtIndex:i] isEqualToString:@"全方位健康管理"] || [[hadertitlearr objectAtIndex:i] isEqualToString:@"promotion"] ){
              
              NSArray *array = @[];
              if ([[hadertitlearr objectAtIndex:i] isEqualToString:@"皇牌服務"]) {
                  array = [menuarr objectAtIndex:0];
              } else if([[hadertitlearr objectAtIndex:i] isEqualToString:@"全方位健康管理"]) {
                  array = [menuarr objectAtIndex:1];
              }else if ([[hadertitlearr objectAtIndex:i] isEqualToString:@"promotion"]){
                  array = [menuarr objectAtIndex:2];
              }
              
                for (NSUInteger j = 0; j < array.count; ++j) {
                    HYBCellModel *cellModel = [[HYBCellModel alloc] init];
                    //cellModel.title = [NSString stringWithFormat:@"young+：section=%ld, row=%ld", i, j];
                    
                    //NSLog(@"indexPath.row %ld",(long)indexPath.row);
                    NSDictionary *dic = [array objectAtIndex:j];
                    //NSLog(@"cell dic %@",dic);
                    NSString *subtitle = [dic valueForKey:@"title"];
                    cellModel.title = subtitle;
                    [itemArray addObject:cellModel];
                }
            }
        
        
          
          
      
      sectionModel.cellModels = itemArray;
        //NSLog(@"数据来源 ： %@",sectionModel);
      
      [_sectionDataSources addObject:sectionModel];
    }
  }
  //NSLog(@"_sectionDataSources 数据来源 ： %@",_sectionDataSources);
  return _sectionDataSources;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  //return self.sectionDataSources.count;
    return indexArray.count;  //5
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    HYBSectionModel *sectionModel = self.sectionDataSources[section];
    return sectionModel.isExpanded ? sectionModel.cellModels.count : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentfier forIndexPath:indexPath];
  MenuTbCell *cell = [MenuTbCell createCellWithTableView:tableView];
    
  HYBSectionModel *sectionModel = self.sectionDataSources[indexPath.section];
  HYBCellModel *cellModel = sectionModel.cellModels[indexPath.row];
  //cell.textLabel.text = cellModel.title;
    
    
  [cell setCellText:cellModel.title];
  
  return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  HYBHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderIdentifier];
    HYBSectionModel *sectionModel = self.sectionDataSources[section];
    view.model = sectionModel;
    view.expandCallback = ^(BOOL isExpanded) {
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:section]
                 withRowAnimation:UITableViewRowAnimationFade];
    };
    
    BOOL isMul = false;
    islogin = [[DataSource getInstance]getLoginFlag];
    if (islogin) {
        if (section ==1 || section ==2 || section ==3) {
            isMul = TRUE;
        }
    } else {
        if (section ==0 || section ==1 || section ==2) {
            isMul = TRUE;
        }
    }
    
    if (isMul) {
        //toggle section cells
      //  NSLog(@"Section chick have Details");
    } else {
        UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,UISCREEN_WIDTH,40)];
        v.tag = section;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleSection:)];
        [v addGestureRecognizer:tap];
        [view addSubview:v];
    }
   
  
  return view;
}

-(void) toggleSection:(UITapGestureRecognizer *)tap {
    UIView *v = tap.view;
    
    BOOL isMul = false;
    int aboutvcVtag = 3;
    int contaceVtag = 4;
    int loginvcVtag = 5;
    islogin = [[DataSource getInstance]getLoginFlag];
    if (islogin) {
        if (v.tag==1 || v.tag==2 || v.tag==3) {
            isMul = TRUE;
        }
        aboutvcVtag = 4;
        contaceVtag = 5;
        loginvcVtag = 6;
    } else {
        if (v.tag==0 || v.tag==1 || v.tag==2) {
            isMul = TRUE;
        }
    }
    //NSLog(@"menu chick %ld",(long)v.tag);
    if (isMul) {
        //toggle section cells
       // NSLog(@"Section chick have Details");
    }else if (v.tag == aboutvcVtag){
        aboutUsSwiftVC *vc_aboutUSswift = [[aboutUsSwiftVC alloc]init];
        //[self presentViewController:vc_aboutUSswift animated:YES completion:nil];  //推一个子视图覆盖
        [self.navigationController pushViewController:vc_aboutUSswift animated:YES];   //同一个navigationController。推出子视图
    }else if (v.tag == 0 && islogin){
        
        getreportvc = [[getReportVC alloc]init];
        getreportvc.itemDatasource = [DataPersist readValuePre:@"wpuid"] ; //用户UID
        [self.navigationController pushViewController:getreportvc animated:true];
        
    }else if (v.tag == loginvcVtag){
        
        if (islogin) {
            NSLog(@"已经登陆");
            [self logoutAlert:@"登出" message:@"您確定登出嗎？"];
        }else{
             NSLog(@"没有登陆");
            if (LoginVC == nil) {
                LoginVC = [[LoginViewController3 alloc]init];
            }
            //[self presentViewController:vc_aboutUSswift animated:YES completion:nil];  //推一个子视图覆盖
            [self.navigationController pushViewController:LoginVC animated:YES];   //同一个navigationController。推出子视图
        }
        
        
        
    }else if (v.tag == contaceVtag){  //联系我们
        
        if (contvc2 == nil) {
            contvc2 = [[contactTVC2 alloc]init];
        }
        [contvc2 setMenutype:0];  //设置菜单类型，默认状态
        //[self presentViewController:vc_aboutUSswift animated:YES completion:nil];  //推一个子视图覆盖
        [self.navigationController pushViewController:contvc2 animated:YES];   //同一个navigationController。推出子视图
    }else {
        NSLog(@"Section chick only");
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  return 60;
}
//被选择行  cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    int provcnum = 2;
    NSInteger secnum = indexPath.section;
    NSInteger rownum = indexPath.row;
    if (islogin) {
        secnum =  (indexPath.section - 1) > 0 ? indexPath.section - 1 : 0;
        //secnum =  (indexPath.section - 1) > 0 ? rownum : 0;
        provcnum = 3;
    }
    
    
//    NSLog(@"indexPath.section  %ld",secnum);
//    NSLog(@"indexPath.row  %ld",rownum);
//    NSArray *array = [menuarr objectAtIndex:indexPath.section];
//    NSDictionary *dic = [array objectAtIndex:indexPath.row];
    NSArray *array = [menuarr objectAtIndex:secnum];
    NSDictionary *dic = [array objectAtIndex:rownum];
    //NSString *str = [dic valueForKey:@"title"];
    //NSLog(@"didSelectRow %@",str);
    //[[MyDataSource getInstance]setCityName:str];
    
    //NSString *itemDataSource = [dicrow valueForKey:@"id"];title
    //NSString *itemDataSource = [dicrow valueForKey:@"title"];
    NSString *itemDataSource = [[NSString alloc] init];
    //NSNumber *B = [NSNumber numberWithInt:123456];
    NSNumber *B = [dic valueForKey:@"detail"];
    itemDataSource = [NSString stringWithFormat:@"%@",B];
    NSLog(@"itemDataSource  %@",itemDataSource);
    
    
    //islogin = [[DataSource getInstance]getLoginFlag];  //判断是否登录
    
    if(indexPath.section == provcnum){
        proTVC = [[promotionTVC alloc]init];
        proTVC.itemDatasource = itemDataSource;
        [self.navigationController pushViewController:proTVC animated:true];
    }else{
        itemVc = [[ItemViewController alloc]init];
        itemVc.itemDatasource = itemDataSource;
        [self.navigationController pushViewController:itemVc animated:true];
    }
    
}

-(void)logoutAlert:(NSString *)title message:(NSString *)message{  //警告弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"您確定登出嗎？ 點擊OK");
        [DataPersist writeValuePre:@"0" key:@"loginStatus"];
        [DataPersist writeValuePre:@"0" key:@"wpuid"];
        [self gotorootVC];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)gotorootVC{
    dispatch_async(dispatch_get_main_queue(), ^{  //get 主线程
        //NSLog(@"currentThread %@ ",[NSThread currentThread]);
        [[DataSource getInstance]setLoginFlag:false]; //取消登錄狀態
        [self.navigationController popToRootViewControllerAnimated:YES]; //IOS 返回根视图
    });
    
}

@end
